package com.project.basis.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.project.basis.receiver.ReceiverCallback;

import java.util.Objects;


public abstract class BaseFragment extends Fragment {

    /**
     * 广播
     */
    protected BaseBroadcastReceiver baseBroadcastReceiver;
    /**
     * 广播回调
     */
    protected ReceiverCallback baseReceiverCallback;
    /**
     * View
     */
    protected View parentView;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(getContentViewId(), container, false);
        parentView = view;
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(savedInstanceState);
        bindViewData(savedInstanceState);
        if (this instanceof ReceiverCallback) {
            baseReceiverCallback = (ReceiverCallback) this;
        }
    }

    protected abstract void initView(Bundle savedInstanceState);

    protected abstract void bindViewData(Bundle savedInstanceState);

    protected abstract int getContentViewId();

    //注册广播方法
    protected void registerBroadcast(String... actions) {
        baseBroadcastReceiver = new BaseBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        for (String action : actions) {
            intentFilter.addAction(action);
        }
        LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).registerReceiver(baseBroadcastReceiver, intentFilter);
    }

    //取消注册
    protected void unRegisterBroadcast() {
        LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).unregisterReceiver(baseBroadcastReceiver);
    }

    protected class BaseBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (baseReceiverCallback != null && intent != null && !TextUtils.isEmpty(intent.getAction())) {
                baseReceiverCallback.onReceive(intent, intent.getAction());
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (baseBroadcastReceiver != null)
            unRegisterBroadcast();
    }
}
